package com.yingda.electronicscaleadvices.utils;


/**
 * @author wu
 * @since 2023/8/2 8:47
 */
public class MathUtil {

    /**
     * 十进制转十六进制反转
     *
     * @param decimal long
     * @return String
     */
    public static String longConvertHex(long decimal) {

        String hexString = Long.toHexString(decimal).toUpperCase();
        return getRevertStr(hexString);

    }

    /**
     * 十六进制反转后转换十进制转
     *
     * @param hex String
     * @return Long
     */
    public static Long hexConvertLong(String hex) {

        try {
            return Long.parseLong(getRevertStr(hex), 16);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 十六进制反转后转换十进制转，用"0"补全至10位数
     *
     * @param hex String
     * @return Long
     */
    public static String hexConvertLongStr(String hex) {
        try {
            long parseLong = Long.parseLong(getRevertStr(hex), 16);
            String result = String.valueOf(parseLong);
            int length = result.length();
            if (length < 10) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < 10 - length; i++) {
                    sb.append("0");
                }
                sb.append(result);

                return sb.toString();
            }

            return result;


        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串按2位反转
     *
     * @param hex String
     * @return String
     */
    private static String getRevertStr(String hex) {
        StringBuilder tmp = new StringBuilder();
        int length = hex.length();
        for (int i = length; i >= 1; i = i - 2) {
            String substring;
            if (i == 1) {
                substring = hex.substring(0, i);
                substring = "0" + substring;
            } else {
                substring = hex.substring(i - 2, i);
            }
            tmp.append(substring);

        }
        return tmp.toString();
    }


}
